package dsx.lock;

import java.util.Date;
import java.util.List;

import dsx.biz.SuperReq;
import dsx.console.DsxConsole;
import dsx.log.ServLog;
import dsx.macro.ReturnValue;

public class LockReq extends SuperReq {
	int type;	// 0 表锁，1 行锁，2 表解锁，3 行解锁
	List<String> collectionKeys;
	List<String> rowKeys;
	String ownerKey;
	int lockTimeout;

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public List<String> getCollectionKeys() {
		return collectionKeys;
	}

	public void setCollectionKeys(List<String> collectionKeys) {
		this.collectionKeys = collectionKeys;
	}

	public List<String> getRowKeys() {
		return rowKeys;
	}

	public void setRowKeys(List<String> rowKeys) {
		this.rowKeys = rowKeys;
	}

	public String getOwnerKey() {
		return ownerKey;
	}

	public void setOwnerKey(String ownerKey) {
		this.ownerKey = ownerKey;
	}

	public int getLockTimeout() {
		return lockTimeout;
	}

	public void setLockTimeout(int lockTimeout) {
		this.lockTimeout = lockTimeout;
	}

	@Override
	public Object handle() {
		try {
			long lockBegin = new Date().getTime();
			LockAnsw answ = new LockAnsw();
			boolean lockResult = false;
			switch (type) {
			case 0:
				lockResult = DsxLock.lockCollections(collectionKeys, ownerKey, lockTimeout);
				break;
			case 1:
				if (collectionKeys.size() == 1) {
					lockResult = DsxLock.lockRows(collectionKeys.get(0), rowKeys, ownerKey, lockTimeout);
				} else {
					lockResult = DsxLock.lockRows(collectionKeys, rowKeys, ownerKey, lockTimeout);
				}
				break;
			case 2:
				DsxLock.releaseCollections(collectionKeys, ownerKey);
				lockResult = true;
				break;
			case 3:
				if (collectionKeys.size() == 1) {
					DsxLock.releaseRows(collectionKeys.get(0), rowKeys, ownerKey);
				} else {
					DsxLock.releaseRows(collectionKeys, rowKeys, ownerKey);
				}
				lockResult = true;
				break;
			}
			long lockEnd = new Date().getTime();
			if (lockResult) {
				String log = String.format("suc; time:%d; coll:%s; row:%s; owner:%s; timeout:%d",
						lockEnd - lockBegin, listToString(collectionKeys), listToString(rowKeys),
						ownerKey, lockTimeout);
				DsxConsole.out(log, "dsxLock", ServLog.info);
				answ.setRet(ReturnValue.succeed);
			} else {
				String log = String.format("fail; time:%d; coll:%s; row:%s; owner:%s; timeout:%d",
						lockEnd - lockBegin, listToString(collectionKeys), listToString(rowKeys),
						ownerKey, lockTimeout);
				DsxConsole.out(log, "dsxLock", ServLog.info);
				answ.setRet(ReturnValue.failure);
			}
			return answ;
		} catch (Exception ex) {
			return null;
		}
	}

	private static String listToString(List<String> lst) {
		if (lst == null || lst.size() == 0)
			return "";
		if (lst.size() == 1)
			return lst.get(0);
		String ret = lst.get(0);
		for (int i = 1; i < lst.size(); i++) {
			ret = ret + "," + lst.get(i);
		}
		return ret;
	}

}
